package com.jiepos.mpos.inter.websocket.trans;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.PostConstruct;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.jiepos.mpos.biz.transaction.service.LogTransJYLSService;

/**
 * @ClassName: TransMonitor
 * @Description: 交易实时监控
 * @author 孙永
 * @date 2018年1月23日 下午3:51:23
 */
@Component
@ServerEndpoint("/transmonitor")
public class TransMonitor{
	
	private static BlockingQueue<String> queue = new LinkedBlockingQueue<>();
	
	private static List<Session> list = new ArrayList<>();
	
	@Autowired
	private LogTransJYLSService logTransJYLSService;
	
	@PostConstruct
	private void init(){
		TransMonitorThread thread = new TransMonitorThread(list, logTransJYLSService, queue);
		thread.start();
	}
	
	@OnOpen
	public void onOpen(Session session){
		if(!list.contains(session)){
			list.add(session);
		}
	}
	
	@OnError
	public void onError(Throwable thr, Session session){
		if(list.contains(session)){
			list.remove(session);
		}
	}
	
	@OnClose
	public void onClose(Session session, CloseReason closeReason){
		if(list.contains(session)){
			list.remove(session);
		}
	}
	
	@Async
	public static void showTrans(String locTransNo){
		try {
			queue.put(locTransNo);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
